package com.momei.util;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class RedisUtils {

    private static final String TOKEN_KEY = "TOKEN_";

    // 过期时间 毫秒,设置默认1天的时间过期
    private static final long EXPIRATION_TIME = 3600000L * 1;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 保存
     */
    public void setToken2Redis(String username,String token) {
        redisTemplate.opsForValue().set(this.genTokenKey(username), token, EXPIRATION_TIME, TimeUnit.SECONDS);
    }

    /**
     * 取
     */
    public String getTokenFromRedis(String username){
        return (String) redisTemplate.opsForValue().get(this.genTokenKey(username));
    }

    /**
     * 删
     */
    public void delTokenFromRedis(String username){
        redisTemplate.delete(this.genTokenKey(username));
    }

    /**
     * 更新
     */
    public void reSetToken2Redis(String username, String token){
        this.delTokenFromRedis(username);
        this.setToken2Redis(username, token);
    }

    /**
     * 判断是否过期
     */
    public boolean isTokenExpired(String username){
        String tokenFromRedis = this.getTokenFromRedis(username);
        if (StringUtils.isNotBlank(tokenFromRedis)){
            return false;
        }
        return true;
    }
    private String genTokenKey(String username){
        return TOKEN_KEY + username + "_MOMO";
    }
}
